$(document).ready(function() {
    // 文件上传相关变量
    const $regAvatar = $('#reg-avatar');
    const $avatarPreview = $('#avatarPreview');
    const $uploadProgress = $('.upload-progress');
    const $progressFill = $('.progress-fill');
    const $progressText = $('.progress-text');
    let avatarFile = null;

    // 图片预览相关变量
    const $previewModal = $('.preview-modal');
    const $modalImage = $('#modalImage');
    const $modalOverlay = $('.modal-overlay');
    const $closeModal = $('.close-modal');
    const $zoomContainer = $('.image-zoom-container');
    const $zoomIn = $('.zoom-in');
    const $zoomOut = $('.zoom-out');
    const $resetZoom = $('.reset-zoom');
    
    // 缩放相关变量
    let currentScale = 1;
    let isDragging = false;
    let startX = 0;
    let startY = 0;
    let translateX = 0;
    let translateY = 0;

    // 文件上传处理
    $regAvatar.on('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        if (!file.type.match(/^image\/(jpeg|png)$/)) {
            showError($(this), '只支持 jpg、png 格式的图片');
            return;
        }

        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            showError($(this), '图片大小不能超过 10MB');
            return;
        }

        $uploadProgress.show();
        $progressFill.css('width', '0%');
        $progressText.text('0%');

        const reader = new FileReader();
        
        reader.onprogress = function(e) {
            if (e.lengthComputable) {
                const progress = (e.loaded / e.total) * 100;
                updateProgress(progress);
                
                const totalSize = formatFileSize(e.total);
                const loadedSize = formatFileSize(e.loaded);
                $progressText.text(`${Math.round(progress)}% (${loadedSize}/${totalSize})`);
            }
        };

        reader.onload = function(e) {
            const img = new Image();
            
            img.onload = function() {
                $avatarPreview.stop(true).fadeOut(200, function() {
                    $(this).attr('src', e.target.result)
                           .attr('data-original-src', e.target.result)
                           .fadeIn(200);
                });
                
                updateProgress(100);
                setTimeout(() => {
                    $uploadProgress.fadeOut();
                }, 500);
                
                avatarFile = file;
            };
            
            img.onerror = function() {
                showError($regAvatar, '图片加载失败，请重试');
                resetAvatarUpload();
            };
            
            img.src = e.target.result;
        };

        reader.onerror = function() {
            showError($regAvatar, '图片读取失败，请重试');
            resetAvatarUpload();
        };

        reader.readAsDataURL(file);
    });

    // 点击头像预览图片
    $avatarPreview.on('click', function() {
        const imgSrc = $(this).attr('data-original-src') || $(this).attr('src');
        if (imgSrc.includes('svg')) return;
        
        resetZoom();
        
        $modalImage.attr('src', imgSrc)
                  .css('max-width', 'none')
                  .css('max-height', '80vh');
        
        $previewModal.css({
            display: 'flex',
            opacity: 0
        }).animate({
            opacity: 1
        }, 300);
        
        $('body').css('overflow', 'hidden');
    });

    // 缩放功能
    $zoomIn.on('click', function() {
        if (currentScale < 3) {
            currentScale += 0.5;
            updateImageTransform();
        }
    });

    $zoomOut.on('click', function() {
        if (currentScale > 0.5) {
            currentScale -= 0.5;
            updateImageTransform();
        }
    });

    $resetZoom.on('click', resetZoom);

    // 更新图片变换
    function updateImageTransform() {
        const transform = `scale(${currentScale}) translate(${translateX / currentScale}px, ${translateY / currentScale}px)`;
        $modalImage.css({
            'transform': transform,
            'transform-origin': 'center center',
            'transition': 'transform 0.2s ease-out'
        });
    }

    // 重置缩放
    function resetZoom() {
        currentScale = 1;
        translateX = 0;
        translateY = 0;
        updateImageTransform();
        $modalImage.css('cursor', 'grab');
    }

    // 拖动功能
    $modalImage.on('mousedown', function(e) {
        if (currentScale > 1) {
            isDragging = true;
            startX = e.clientX - translateX;
            startY = e.clientY - translateY;
            $modalImage.css('cursor', 'grabbing');
            e.preventDefault();
        }
    });

    $(document).on('mousemove', function(e) {
        if (isDragging) {
            translateX = e.clientX - startX;
            translateY = e.clientY - startY;
            
            const maxTranslate = (currentScale - 1) * $modalImage.width() / 2;
            translateX = Math.max(-maxTranslate, Math.min(maxTranslate, translateX));
            translateY = Math.max(-maxTranslate, Math.min(maxTranslate, translateY));
            
            updateImageTransform();
        }
    });

    $(document).on('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            $modalImage.css('cursor', 'grab');
        }
    });

    // 鼠标滚轮缩放
    $zoomContainer.on('wheel', function(e) {
        e.preventDefault();
        const delta = e.originalEvent.deltaY;
        const zoomSpeed = 0.1;
        
        if (delta < 0 && currentScale < 3) {
            currentScale = Math.min(3, currentScale + zoomSpeed);
            updateImageTransform();
        } else if (delta > 0 && currentScale > 0.5) {
            currentScale = Math.max(0.5, currentScale - zoomSpeed);
            updateImageTransform();
        }
    });

    // 关闭预览模态框
    function closePreviewModal() {
        $previewModal.animate({
            opacity: 0
        }, 300, function() {
            $(this).css('display', 'none');
            $('body').css('overflow', '');
            resetZoom();
        });
    }

    // 双击图片重置缩放
    $modalImage.on('dblclick', resetZoom);

    $closeModal.on('click', function(e) {
        e.stopPropagation();
        closePreviewModal();
    });

    $modalOverlay.on('click', closePreviewModal);

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $previewModal.is(':visible')) {
            closePreviewModal();
        }
    });

    $modalImage.on('click', function(e) {
        e.stopPropagation();
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 更新进度条
    function updateProgress(progress) {
        progress = Math.min(100, Math.round(progress));
        $progressFill.css('width', `${progress}%`);
    }

    // 重置头像上传状态
    function resetAvatarUpload() {
        $avatarPreview.fadeOut(200, function() {
            $(this).attr('src', 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'120\' height=\'120\' viewBox=\'0 0 120 120\'%3E%3Crect width=\'120\' height=\'120\' fill=\'%23f0f0f0\'/%3E%3Cpath d=\'M60 40c11 0 20 9 20 20s-9 20-20 20-20-9-20-20 9-20 20-20zm0-8c-15.5 0-28 12.5-28 28s12.5 28 28 28 28-12.5 28-28-12.5-28-28-28z\' fill=\'%23ccc\'/%3E%3C/svg%3E')
                   .removeAttr('data-original-src')
                   .fadeIn(200);
        });
        avatarFile = null;
        $uploadProgress.hide();
        $progressFill.css('width', '0%');
        $progressText.text('0%');
    }

    // 导出变量和函数
    window.avatarUpload = {
        resetAvatarUpload,
        avatarFile
    };
}); 